package com.xmall.auth.controller;


import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xmall.auth.entity.SysPermission;
import com.xmall.auth.entity.SysRole;
import com.xmall.auth.service.ISysRoleService;
import com.xmall.auth.service.ISysUserService;
import com.xmall.auth.service.XmallUserDetailsService;
import com.xmall.auth.xmallauth.jwt.model.LoginUser;
import com.xmall.auth.xmallauth.jwt.util.JwtTokenUtil;
import com.xmall.common.base.BaseController;
import com.xmall.common.config.CommonPage;
import com.xmall.common.config.CommonResult;
import com.xmall.common.model.SysUser;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.security.Principal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author liuzh
 * @since 2020-05-16
 */
@Api(tags = "SysUserController", description = "后台人员管理")
@RestController
@RequestMapping("/user")
public class SysUserController extends BaseController {
    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private XmallUserDetailsService xmallUserDetailsService;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Value("${jwt.tokenHeader}")
    private String tokenHeader;
    @Value("${jwt.tokenPrefix}")
    private String tokenPrefix;

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public CommonResult login(@RequestBody LoginUser loginUser) {
        Map<String, String> tokenMap = sysUserService.login(loginUser);
        return CommonResult.success(tokenMap);
    }

    @RequestMapping(value = "/logout", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult logout() {
        return CommonResult.success(null);
    }

    @RequestMapping(value = "/info", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult getAdminInfo(Principal principal) {
        if (principal == null) {
            return CommonResult.unauthorized(null);
        }
        String username = principal.getName();
        Map<String, Object> adminInfo = sysUserService.getAdminInfo(username);
        return CommonResult.success(adminInfo);
    }

    @RequestMapping(value = "/refreshToken", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult refreshToken(HttpServletRequest request) {
        String token = request.getHeader(tokenHeader);
        String refreshToken = jwtTokenUtil.refreshHeadToken(token);
        if (refreshToken == null) {
            return CommonResult.failed("token已经过期！");
        }
        Map<String, String> tokenMap = new HashMap<>();
        tokenMap.put("token", refreshToken);
        tokenMap.put("tokenPrefix", tokenPrefix);
        return CommonResult.success(tokenMap);
    }

    @RequestMapping(value = "/register", method = RequestMethod.POST)
    public CommonResult registerUser(@RequestBody SysUser sysUser) {
        boolean save = sysUserService.registerUser(sysUser);
        if(!save){
            return CommonResult.failed();
        }
        return CommonResult.success(save);
    }

    @ApiOperation("删除后台用户")
    @RequestMapping(value = "/delete/{id}", method = RequestMethod.POST)
    public CommonResult delete(@PathVariable Long id) {
        boolean delete = sysUserService.deleteUser(id);
        if(!delete){
            return CommonResult.failed();
        }
        return CommonResult.success(delete);
    }

    @ApiOperation("更新后台用户")
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult update(@RequestBody SysUser sysUser) {
        boolean update = sysUserService.updateUser(
                sysUser,
                new QueryWrapper<SysUser>()
                        .lambda().eq(SysUser::getId, sysUser.getId())
        );
        if(!update){
            return CommonResult.failed();
        }
        return CommonResult.success(update);
    }


    @ApiOperation("分页查询后台用户")
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult<CommonPage<SysUser>> list(@RequestParam(value = "keyword", required = false) String keyword,
                                                  @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize,
                                                  @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum) {

        Page<SysUser> page = new Page<>(pageNum, pageSize);
        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
        if(!StrUtil.isEmpty(keyword)){
            queryWrapper.like("user_name",keyword);
        }
        IPage<SysUser> userIPage = sysUserService.page(page, queryWrapper);
        userIPage.getRecords().stream().forEach(sysUser -> sysUser.setUserPassword(null));
        return CommonResult.success(CommonPage.restPage(userIPage));
    }

    @ApiOperation("给用户分配角色")
    @RequestMapping(value = "/role/update", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult updateRole(@RequestParam("adminId") Long adminId,
                                   @RequestParam("roleIds") List<Long> roleIds) {
        int count = sysUserService.updateRole(adminId, roleIds);
        if (count >= 0) {
            return CommonResult.success(count);
        }
        return CommonResult.failed();
    }

    @ApiOperation("获取指定用户的角色")
    @RequestMapping(value = "/role/{adminId}", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult<List<SysRole>> getRoleList(@PathVariable Long adminId) {
        List<SysRole> roleList = sysUserService.getRoleList(adminId);
        return CommonResult.success(roleList);
    }

    @ApiOperation("给用户分配+-权限")
    @RequestMapping(value = "/permission/update", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult updatePermission(@RequestParam Long adminId,
                                         @RequestParam("permissionIds") List<Long> permissionIds) {
        int count = sysUserService.updatePermission(adminId, permissionIds);
        if (count > 0) {
            return CommonResult.success(count);
        }
        return CommonResult.failed();
    }

    @ApiOperation("获取用户所有权限（包括+-权限）")
    @RequestMapping(value = "/permission/{adminId}", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult<List<SysPermission>> getPermissionList(@PathVariable Long adminId) {
        List<SysPermission> permissionList = sysUserService.getPermissionList(adminId);
        return CommonResult.success(permissionList);
    }
}
